package com.shop.merchant.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.config.JwtUtils;
import com.shop.ex.ShoppingException;
import com.shop.feignClient.AliyunClient;
import com.shop.merchant.Interceptor.GetMerchantInfoInterceptor;
import com.shop.merchant.mapper.MerchantMapper;
import com.shop.merchant.po.Merchant;
import com.shop.merchant.po.dto.MerchantDto;
import com.shop.merchant.service.MerchantService;
import com.shop.po.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import static com.shop.common.comstant.Constant.*;

/**
 * <p>
 * 商家信息 服务实现类
 * </p>
 *
 * @author banxia
 * @since 2023-02-23
 */
@Service
@Slf4j
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliyunClient aliyunClient;

    @Override
    public R sendMessage(String phone, String type) {
        //根据传入的类型来判断验证码的储存位置,若为空则表示 type无效
        String redisKeyPre = IfExistType(type);
        if (Strings.isEmpty(redisKeyPre)){
            ShoppingException.ThrowShoppingException("type不符合要求，请填写实际要求");
        }
        String redisKey=redisKeyPre+phone;
        return aliyunClient.sendMessage(redisKey,phone);
    }

    @Override
    public R uploadFile(MultipartFile file, String type) {
        String pathPre = IfExistType(type);
        if (Strings.isBlank(pathPre)){
            ShoppingException.ThrowShoppingException("type不符合要求，请填写实际要求");
        }
        Merchant merchant = GetMerchantInfoInterceptor.getMerchant();
        if (merchant==null || merchant.getId()==null){
            ShoppingException.ThrowShoppingException("用户登录失效");
        }
        String path=pathPre+merchant.getId();
        log.info("------------------------------------------");
        log.info("开始feign调用");
        log.info("------------------------------------------");
        R r = aliyunClient.uploadOssFile(file, path);
        log.info("------------------------------------------");
        log.info("feign调用完成");
        log.info("------------------------------------------");
        return r;
    }

    @Override
    public void editMerchantInfo(MerchantDto merchantDto, String password) {
        Merchant merchant = GetMerchantInfoInterceptor.getMerchant();
        if (merchant == null) {
            ShoppingException.ThrowShoppingException("未登录/登录失效，请重新登录");
        }
        Merchant editMerchant=new Merchant();
        if (Strings.isBlank(password)) {
            //（1）编辑用户基本信息
            BeanUtils.copyProperties(merchantDto,editMerchant);
            editMerchant.setId(merchant.getId());
            merchantMapper.updateById(editMerchant);
        }else{
            //（2）修改密码到数据库
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            editMerchant.setId(merchant.getId());
            editMerchant.setPassword(md5Password);
            merchantMapper.updateById(editMerchant);
        }
    }

    @Override
    public MerchantDto getMerchantInfo() {
        Merchant merchant = GetMerchantInfoInterceptor.getMerchant();
        if (merchant == null) {
            ShoppingException.ThrowShoppingException("未登录/登录失效，请重新登录");
        }
        MerchantDto merchantDto = new MerchantDto();
//        BeanUtils.copyProperties(merchant,merchantDto);
        Merchant merchant1 = merchantMapper.selectById(merchant.getId());
        BeanUtils.copyProperties(merchant1,merchantDto);
        return merchantDto;
    }


    //密码登录
    @Override
    public String loginByPassword(String account, String password) {
        LambdaQueryWrapper<Merchant> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Merchant::getAccount,account);
        Merchant merchant = merchantMapper.selectOne(wrapper);
        if (merchant == null) {
            ShoppingException.ThrowShoppingException("用户账号不存在");
        }
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(merchant.getPassword())) {
            ShoppingException.ThrowShoppingException("密码错误");
        }
        merchant.setPassword(null);
        //将用户信息转换为token
        String merchantJson = JSONObject.toJSONString(merchant);
        String token = JwtUtils.getJwtToken(merchantJson);
        return token;
    }

    //验证码登录
    @Override
    public String loginByCode(String phone, String code) {
        LambdaQueryWrapper<Merchant> wrapper=new LambdaQueryWrapper<>();
        //校验验证码是否正确
        String MerchantLoginCodePre = IfExistType(MerchantLoginType);
        String RightCode = redisTemplate.opsForValue().get(MerchantLoginCodePre + phone);
        if (Strings.isBlank(RightCode) || !RightCode.equals(code)){
            ShoppingException.ThrowShoppingException("验证码错误");
        }
        //根据手机号查询用户
        wrapper.eq(Merchant::getPhone,phone);
        Merchant merchant = merchantMapper.selectOne(wrapper);
        if (merchant == null) {
            ShoppingException.ThrowShoppingException("用户账号不存在");
        }
        merchant.setPassword(null);
        //将用户信息转换为token
        String merchantJson = JSONObject.toJSONString(merchant);
        String token = JwtUtils.getJwtToken(merchantJson);
        return token;
    }


    //注册
    @Override
    public void register(MerchantDto merchantDto, String password,String code) {
        //（1）验证 验证码是否正确
        String phone = merchantDto.getPhone();
        String redisKeyPre = IfExistType(MerchantRegisterType);
        String rightCode = redisTemplate.opsForValue().get(redisKeyPre + phone);
        if (rightCode==null || !rightCode.equals(code)){
            ShoppingException.ThrowShoppingException("验证码错误");
        }
        //（2）新增用户信息
        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(merchantDto,merchant);
        merchant.setId(null);//自增
        String newPassword= DigestUtils.md5DigestAsHex(password.getBytes());//加密后的密码
        merchant.setPassword(newPassword);
        merchant.setStatus(1);
        merchant.setType("merchant");
        int i = merchantMapper.insert(merchant); //若这里(手机号/账号ID)不唯一也会抛出异常
        if (i==0){
            ShoppingException.ThrowShoppingException("注册失败");
        }
    }


}
